package com.ruoyi.common.controller;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.domain.po.BasePO;
import com.ruoyi.common.domain.qo.BaseQO;
import com.ruoyi.common.enums.BaseIsDeletedEnum;
import com.ruoyi.common.mapper.BaseMapper;
import com.ruoyi.common.service.BaseService;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

public abstract class BasicController<P extends BasePO, Q extends BaseQO<P>, M extends BaseMapper<P, Q>, S extends BaseService<P, Q, M>> {
    @Autowired
    private S service;

    @Value("#{'${server.ignore-paths}'.split(',')}")
    private List<String> ignoreUrls = new ArrayList<>();

    public LoginUser getLoginUser() {
        return SecurityUtils.getLoginUser();
    }

    public Long getUserId() {
        return SecurityUtils.getUserId();
    }
    /**
     * 设置请求分页数据
     */
    protected void startPage()
    {
        PageUtils.startPage();
    }

    @PostMapping
    public AjaxResult add(@RequestBody P entity) {
        if (!this.isAnonymous()) {
            entity.setCreateId(this.getUserId());
            entity.setModifiedId(this.getUserId());
        }
        return AjaxResult.success(service.insert(entity));
    }

    @DeleteMapping
    public AjaxResult delete(@RequestBody Q q) {
        return AjaxResult.success(service.delete(q));
    }
    public boolean isAnonymous() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 创建解析器
        AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
// 判断是否为匿名用户
        /*if (trustResolver.isAnonymous(authentication)) {
            // 是匿名用户，处理匿名访问逻辑，例如跳过获取用户详情
            return "anonymous user";
        } else {
            // 是已认证用户，可以安全地获取用户信息
            YourUserDetails userDetails = (YourUserDetails) authentication.getPrincipal();
            return "authenticated user: " + userDetails.getUsername();
        }*/
        return trustResolver.isAnonymous(authentication);
    }
    @PutMapping
    public AjaxResult update(@RequestBody Q q) {
        P updatePO = q.getUpdatePO();
        if (!this.isAnonymous()) {
            updatePO.setModifiedId(this.getUserId());
        }
        return AjaxResult.success(service.update(q));
    }

    @PutMapping("/updateSelective")
    public AjaxResult updateSelective(@RequestBody Q q) {
        P updatePO = q.getUpdatePO();
        if (!this.isAnonymous()) {
            updatePO.setModifiedId(this.getUserId());
        }
        return AjaxResult.success(service.updateSelective(q));
    }

    @PutMapping("/batchUpdate")
    public AjaxResult batchUpdate(@RequestBody List<Q> qs) {
        return AjaxResult.success(service.batchUpdate(qs));
    }

    @PutMapping("/batchUpdateSelective")
    public AjaxResult batchUpdateSelective(@RequestBody List<Q> qs) {
        return AjaxResult.success(service.batchUpdateSelective(qs));
    }

    @PostMapping("/batchInsert")
    public AjaxResult batchInsert(@RequestBody List<P> ps) {
        return AjaxResult.success(service.batchInsert(ps));
    }

    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(service.selectById(id));
    }

    @GetMapping("/list")
    public TableDataInfo list(Q q) {
        startPage();
        return getDataTable(service.select(q));
    }

    @GetMapping("/list_exists")
    public TableDataInfo listExists(Q q) {
        startPage();
        q.setIsDeleted(BaseIsDeletedEnum.EXISTS);
        return getDataTable(service.select(q));
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }
}
